package com.example.sparkchaindemo;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.sparkchain.core.rtasr.RTASR;
import com.iflytek.sparkchain.core.rtasr.RTASRCallbacks;

import java.util.ArrayList;
import java.util.List;

/*************************
 * 实时语音转写Demo (仅麦克风输入)
 * create by wxw
 * 2024-12-16
 * **********************************/
public class RTASRActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "AEELog";
    private String RTASRAPIKEY = "";
    private Spinner sp_language;
    TextView tv_result, tv_statusInfo;
    private Button btn_audio_start;
    private RTASR mRTASR;
    boolean isrun = false;
    String asrFinalResult = "识别结果：\n";
    String transFinalResult = "翻译结果：\n";
    private ASRMode language = ASRMode.CN;
    private List<String> languageList = new ArrayList<String>();

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ai_rtasr_audio_btn) {
            if (isrun) return; // 防止重复启动
            tv_result.setText("识别结果：\n");
            asrFinalResult = "识别结果：\n";
            transFinalResult = "翻译结果：\n";

            new Thread(new Runnable() {
                @Override
                public void run() {
                    getPermission(); // 获取权限后会自动调用 runRtasr_Audio
                }
            }).start();
        } else if (id == R.id.ai_rtasr_btn_stop) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mRTASR != null && isrun) {
                        mRTASR.stopListener();
                        isrun = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn_audio_start.setText("开始麦克风识别");
                                btn_audio_start.setEnabled(true);
                                tv_statusInfo.setText("点击开始识别");
                            }
                        });
                    }
                }
            }).start();
        }
    }

    private enum ASRMode {
        CN,
        EN
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ai_rtasr);
        languageList.add("中文");
        languageList.add("英文");
        tv_result = findViewById(R.id.ai_rtasr_asrResult);
        tv_result.setMovementMethod(new ScrollingMovementMethod());
        tv_statusInfo = findViewById(R.id.ai_rtasr_testAudioPath); // 复用此TextView显示状态
        sp_language = findViewById(R.id.ai_rtasr_language);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, languageList);
        sp_language.setAdapter(adapter);
        sp_language.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                String selectedItem = adapterView.getItemAtPosition(position).toString();
                Log.d(TAG, "language:" + selectedItem);
                if ("中文".equals(selectedItem)) {
                    language = ASRMode.CN;
                } else {
                    language = ASRMode.EN;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        btn_audio_start = findViewById(R.id.ai_rtasr_audio_btn);
        btn_audio_start.setOnClickListener(this);
        findViewById(R.id.ai_rtasr_btn_stop).setOnClickListener(this);
        init();
        tv_statusInfo.setText("点击开始识别");
    }

    protected void init() {
        RTASRAPIKEY = getResources().getString(R.string.RTASRAPIKEY);
        mRTASR = new RTASR(RTASRAPIKEY);//创建RTASR实例
        mRTASR.registerCallbacks(mRtAsrCallbacks);//注册监听回调
    }


    RTASRCallbacks mRtAsrCallbacks = new RTASRCallbacks() {
        @Override
        public void onResult(RTASR.RtAsrResult result, Object usrTag) {
            String data = result.getData();
            String rawResult = result.getRawResult();
            int status = result.getStatus();
            String sid = result.getSid();
            String src = result.getTransResult().getSrc();
            String dst = result.getTransResult().getDst();
            int transStatus = result.getTransResult().getStatus();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (status == 1) {
                        String asrText = asrFinalResult + data;
                        tv_result.setText(asrText);
                        toend(tv_result);
                    } else if (status == 2) {
                        asrFinalResult = asrFinalResult + data;
                    } else if (status == 3) {
                        tv_result.setText(asrFinalResult);
                        toend(tv_result);
                        if (isrun) {
                            if (mRTASR != null) {
                                mRTASR.stopListener();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    btn_audio_start.setText("开始麦克风识别");
                                    btn_audio_start.setEnabled(true);
                                    tv_statusInfo.setText("识别结束");
                                }
                            });
                            isrun = false;
                        }
                    } else if (status == 0) {
                        if (transStatus == 2) {
                            transFinalResult = transFinalResult + dst;
                        } else {
                            String transText = transFinalResult + dst;
                        }
                    }
                }
            });
        }

        @Override
        public void onError(RTASR.RtAsrError error, Object usrTag) {
            int code = error.getCode();
            String msg = error.getErrMsg();
            String sid = error.getSid();
            Log.e(TAG, "RTASR onError: code=" + code + ", msg=" + msg + ", sid=" + sid);
            if (isrun) {
                if (mRTASR != null) {
                    mRTASR.stopListener();
                }
                isrun = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_audio_start.setText("开始麦克风识别");
                        btn_audio_start.setEnabled(true);
                        tv_statusInfo.setText("发生错误: " + msg + " (码: " + code + ")");
                    }
                });
            }
        }

        @Override
        public void onBeginOfSpeech() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "onBeginOfSpeech");
                    tv_statusInfo.setText("检测到语音开始");
                }
            });
        }

        @Override
        public void onEndOfSpeech() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "onEndOfSpeech");
                    tv_statusInfo.setText("检测到语音结束，处理中...");
                    // SDK会自动发送结束帧，通常不需要手动stopListener，除非用户点击停止按钮
                }
            });
        }
    };

    int count = 0;//用户自定义标识

    // 文件转写功能已移除
    // private void runRtasr_file(ASRMode mode) { ... }

    private void getPermission() {
        XXPermissions.with(this)
                .permission("android.permission.RECORD_AUDIO", "android.permission.READ_PHONE_STATE") // 确保权限声明与实际需求一致
                .request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean all) {
                Log.d(TAG, "SDK获取系统权限成功:" + all);
                if (all) {
                    runRtasr_Audio(language);
                } else {
                    Log.e(TAG, "部分权限未授予，无法开始录音");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_statusInfo.setText("必要权限未授予，无法开始录音");
                        }
                    });
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                Log.e(TAG, "onDenied:权限获取失败. Denied: " + denied.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_statusInfo.setText("权限获取失败，无法开始录音");
                    }
                });
                if (quick) {
                    Log.e(TAG, "onDenied:被永久拒绝授权，请手动授予权限");
                    XXPermissions.startPermissionActivity(RTASRActivity.this, denied);
                }
            }
        });
    }


    private void runRtasr_Audio(ASRMode mode) {
        if (isrun) return; // 再次检查，防止并发问题
        count++;
        isrun = true;
        if (mRTASR == null) {
            mRTASR = new RTASR(RTASRAPIKEY);
            mRTASR.registerCallbacks(mRtAsrCallbacks);
        }

        mRTASR.transType("normal");
        mRTASR.transStrategy(2);
        if (mode == ASRMode.CN) {
            mRTASR.lang("cn");
            mRTASR.targetLang("en");
        } else {
            mRTASR.lang("en");
            mRTASR.targetLang("cn");
        }

        asrFinalResult = "识别结果：\n";
        transFinalResult = "翻译结果：\n";
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_result.setText(asrFinalResult);
                tv_statusInfo.setText("录音中...");
                btn_audio_start.setText("录音中...");
                btn_audio_start.setEnabled(false);
            }
        });
        int ret = mRTASR.startListener(count + "");
        Log.d(TAG, "mRTASR.startListener ret:" + ret + "-count:" + count);
        if (ret != 0) {
            isrun = false;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_statusInfo.setText("麦克风转写启动出错，错误码:" + ret);
                    btn_audio_start.setText("开始麦克风识别");
                    btn_audio_start.setEnabled(true);
                }
            });
        }
    }


    /*************************
     * 显示控件自动下移
     * *******************************/
    public void toend(TextView tv) {
        int scrollAmount = tv.getLayout().getLineTop(tv.getLineCount()) - tv.getHeight();
        if (scrollAmount > 0) {
            tv.scrollTo(0, scrollAmount + 10);
        }
    }

}
